//
//  NSObject+Notification.m
//  青旅OA
//
//  Created by qlwl on 16/4/22.
//  Copyright © 2016年 qlwl. All rights reserved.
//

#import "NSObject+Notification.h"
#import <objc/runtime.h>

//static char notKey;
static char notArray[50];//最大是50个
static NSMutableDictionary *dict = nil;

@implementation NSObject (Notification)
-(void)addObserverWithName:(NSString *)aName object:(id)anObject block:(void (^)(NSNotification * notific))notClick
{
    if (aName == nil) {//不能添加一个没有名字的通知
        NSLog(@"不能添加一个没有名字的通知");
        return;
    }
    //记录个数
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        dict = [[NSMutableDictionary alloc] init];
    });
    if (dict.allKeys.count >=50) {
        NSLog(@"超过最大容量了");
        return;
    }
    if (dict[aName] == nil) {//一个对象不能添加重名的通知
        dict[aName] = [NSNumber numberWithInteger:[dict.allKeys count]];
        NSLog(@"%@",dict);
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notClick:) name:aName   object:anObject];
    objc_setAssociatedObject(self, &notArray[[dict[aName] intValue]],notClick, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (void)notClick:(NSNotification *)notific
{
    void (^block)(NSNotification *) = (void (^)(NSNotification *))objc_getAssociatedObject(self, &notArray[[dict[notific.name] intValue]]);
    if (block) {
        block(notific);
    }
}
- (void)removeObserverSelf
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
+ (void) postNotificationName:(NSString *)aName object:(id)anObject
{
    [[NSNotificationCenter defaultCenter] postNotificationName:aName object:anObject];
}

@end
